from datetime import timedelta, datetime
from typing import Union

from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from starlette import status

from application.handle_exception import form_unauthorized_exception
from application.utils import get_rich_logger
from domain.authentication import TokenData, User, Admin
from authentication.utils import *
from db.metastore import rest_authentication

pwd_context = CryptContext(
    schemes=["bcrypt"],
    deprecated="auto"
)
oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="/fiat/api/auth/token"
)
logger = get_rich_logger()


# passlib context & helper method
def verify_password(plain_password, hashed_password):
    logger.info("Verifying password...")
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.hash(password)


def encode_jwt_payload(data: dict, expires_delta: Union[timedelta, None] = None):
    to_encode = data.copy()
    if expires_delta:
        expire: datetime = get_local_datetime() + expires_delta
    else:
        expire: datetime = get_local_datetime() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(
        claims=to_encode,
        key=SECRET_KEY,
        algorithm=JwtEncryption.HS256
    )
    return encoded_jwt


# JWT encoding & decoding
def create_access_token(data: dict):
    logger.info("Creating access token...")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    ret = encode_jwt_payload(data, access_token_expires)
    return ret


async def decode_jwt_payload(token: str = Depends(oauth2_scheme)):
    logger.info("Decoding jwt...")
    try:
        payload = jwt.decode(
            token=token,
            key=SECRET_KEY,
            algorithms=[JwtEncryption.HS256]
        )
        expire = datetime.fromtimestamp(payload['exp'])
        now = get_local_datetime()
        maybe_expire = now > expire
        if maybe_expire:
            raise form_unauthorized_exception(
                msg="Credentials expired. Please login again."
            )
        subject: str = payload['sub']
        if subject is None:
            raise form_unauthorized_exception(
                msg="Subject empty. Please login again."
            )
        token_data = TokenData(
            uuid=UUID(subject),
            username=payload['name'],
            email=payload['email'],
            password=payload['password']
        )  # username format - "name:email"
    except JWTError:
        raise form_unauthorized_exception(
            msg="Could not validate credentials"
        )
    return token_data


async def get_current_user(jwt_token: TokenData = Depends(decode_jwt_payload)):
    logger.debug(f"Get current user. Token data: {jwt_token.dict()}")
    current_user = User(**jwt_token.dict())
    return current_user


async def auth_with_token(token: TokenData, api: str):
    logger.debug(f"Authenticate user with token: {token.dict()}\n")
    auth_result = await rest_authentication(
        api=api,
        token=token
    )
    logger.debug("Authentication compelte.")
    return auth_result


def form_user_in_db(user_auth_dict: dict):
    try:
        record = user_auth_dict['response']['record']
        body = user_auth_dict['body']
        db_user = UserInDB(
            id=record['id'],
            uuid=record['uuid'],
            username=record['username'],
            email=body['identity'],
            password=body['password'],
            hashed_password=record['hashed_password']
        )
    except KeyError:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Forming response artifact failed due to KeyError.",
            headers={"WWW-authentication": "Bearer"}
        )
    logger.debug("User-in-DB object available.")
    return db_user


async def auth_user_with_token(token: TokenData):
    auth_result = await auth_with_token(
        token=token,
        api="/api/collections/users/auth-with-password"
    )
    if auth_result['status'] == 400:
        raise form_unauthorized_exception(
            msg=auth_result['response']
        )
    user_in_db: UserInDB = form_user_in_db(auth_result)
    return user_in_db


async def user_login(login_token: TokenData):
    user_in_db: UserInDB = await auth_user_with_token(login_token)
    if not verify_password(user_in_db.password, user_in_db.hashed_password):
        raise form_unauthorized_exception(
            msg="Incorrent password / username"
        )
    user_dict = user_in_db.dict()
    user_dict.pop('hashed_password')
    user_dict.pop('id')
    return User(**user_dict)


def form_admin(admin_auth_dict: dict):
    try:
        # admin_record = resposne['admin']['response']
        body = admin_auth_dict['body']
        authenticated_admin = Admin(
            email=body['identity'],
            password=body['password']
        )
    except KeyError:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Forming response artifact failed due to KeyError.",
            headers={"WWW-authentication": "Bearer"}
        )
    return authenticated_admin


async def auth_admin_with_token(token: TokenData):
    auth_result = await auth_with_token(
        token=token,
        api="/api/admins/auth-with-password"
    )
    if auth_result['status'] == 400:
        raise form_unauthorized_exception(
            msg=auth_result['response']
        )
    ret_admin = form_admin(auth_result)
    return ret_admin


async def admin_login(login_token: TokenData):
    admin: Admin = await auth_admin_with_token(login_token)
    logger.info("Successfully login in as admin.")
    return admin


async def login_authentication(login_token: TokenData):
    if login_token.username == "admin":
        logger.info("Try login as admin...")
        admin: Admin = await admin_login(login_token)
        return User(
            uuid=login_token.uuid,
            username=login_token.username,
            email=admin.email,
            password=admin.password,
        )
    else:
        logger.info("Try login as user...")
        user = await user_login(login_token)
        return user


async def check_admin_privilege(token_data: TokenData = Depends(decode_jwt_payload)):
    logger.info("Checking admin privilege with existing JWT.")
    admin_auth = await auth_with_token(
        token=token_data,
        api="/api/admins/auth-with-password"
    )
    ret_admin: Admin = form_admin(admin_auth)
    return ret_admin
